<template>
  <sub-page>
    <main-card>
      <card-top-info title="点数风暴设置"></card-top-info>
      <div class="settingForm">
        <div class="setting-item">
          <div class="setting-item-title">游戏时间</div>
          <div class="setting-item-content">
             <el-input-number v-model="formData.gameTime" :min="1" :step="1" controls-position="right" />
            <span style="margin-left: 15px">分</span>
          </div>
        </div>
        <div class="setting-item">
          <div class="setting-item-title">单次参与价格</div>
          <div class="setting-item-content">
            <el-input-number v-model="formData.perPrice" :min="0.01" :step="0.1" controls-position="right" />
            <span style="margin-left: 15px">元</span>
          </div>
        </div>
        <div class="submit-btn">
          <el-button type="primary" @click="submitSetting">提交</el-button>
        </div>
      </div>

      <!-- 奖项设置 -->
      <div class="award-setting-section">
        <div class="section-title">奖项设置</div>
        <div class="award-table-container">
          <my-table style="height: auto">
            <el-table
              :data="awardData"
              highlight-current-row
              style="width: 100%"
              header-row-class-name="table-header"
            >
              <el-table-column min-width="120" align="center" header-align="center" label="名次">
                <template slot-scope="scope">
                  <span>第{{ scope.$index + 1 }}名</span>
                </template>
              </el-table-column>
              <el-table-column min-width="200" label="奖品名称" prop="prizeName" align="center" header-align="center">
              </el-table-column>
              <el-table-column min-width="120" align="center" header-align="center" label="奖品图片">
                <template slot-scope="scope">
                  <div class="prize-img">
                    <img
                      v-if="scope.row.prizeImg"
                      width="47"
                      height="31"
                      style="border-radius: 4px"
                      :src="scope.row.prizeImg"
                      alt=""
                    />
                    <div v-else class="no-img-placeholder">
                      <i class="el-icon-picture"></i>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="150" align="center" header-align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" @click="editAward(scope.row, scope.$index)">编辑</el-button>
                  <el-button size="mini" type="danger" @click="confirmDeleteAward(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </my-table>
          <!-- 新增奖项按钮 -->
          <div class="add-award-btn" @click="addAward">
            <span class="el-icon-plus"></span>新增奖项
          </div>
        </div>
      </div>

      <!-- 编辑奖项弹窗 -->
      <my-dialog :show="editAwardDialog">
        <div class="dialog-title" slot="title">
          <div class="title-text">{{ currentEditIndex === -1 ? '新增奖项' : '编辑奖项' }}</div>
        </div>
        <div class="edit-form">
          <div class="form-item">
            <div class="form-label">奖品名称</div>
            <div class="form-input">
              <el-input v-model="editForm.prizeName" placeholder="例如：¥1999 人头马1瓶"></el-input>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">奖品图片</div>
            <div class="form-input">
              <div class="image-upload">
                <div class="image-preview">
                  <img v-if="editForm.prizeImg" :src="editForm.prizeImg" alt="" />
                  <div v-else class="no-image">
                    <i class="el-icon-picture"></i>
                  </div>
                </div>
                <el-upload
                  class="upload-btn"
                  :show-file-list="false"
                  :http-request="handleFile"
                  action
                >
                  <el-button type="primary" size="small" icon="el-icon-upload">选择图片</el-button>
                </el-upload>
              </div>
            </div>
          </div>
        </div>
        <div class="dialog-buttons">
          <el-button type="primary" @click="saveAward">保存</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </div>
      </my-dialog>
    </main-card>
  </sub-page>
</template>

<script>
import SubPage from '@/components/subPage';
import MainCard from '@/components/mainCard';
import CardTopInfo from '@/components/cardTopInfo';
import MyTable from '@/components/myTable';
import MyDialog from '@/components/myDialog';
import request from '@/utils/request';
import { getActivityMsg } from '@/api/setting/activitySetting/gameSetting';

export default {
  name: 'PointStorm',
  components: {
    SubPage,
    MainCard,
    CardTopInfo,
    MyTable,
    MyDialog,
  },
  data() {
    return {
      formData: {
        gameTime: 3, // 游戏时间，单位：分钟
        perPrice: 18.8, // 单次参与价格，单位：元
      },
      // 奖项数据
      awardData: [],
      // 编辑奖项弹窗
      editAwardDialog: false,
      currentEditIndex: -1,
      editForm: {
        prizeName: '',
        prizeImg: '',
      },
      tempFile: null,
    };
  },
  created() {
    this.getFormData();
  },
  methods: {
    formValidate() {
      let tmpResult = true;
      if (this.awardData.length === 0) {
        this.$message.error('至少需要设置一个奖项');
        tmpResult = false;
      }
      // 检查所有奖项是否都有奖品名称
      for (let i = 0; i < this.awardData.length; i++) {
        if (!this.awardData[i].prizeName) {
          this.$message.error(`第${i + 1}个奖项的奖品名称不能为空`);
          tmpResult = false;
          break;
        }
      }
      return tmpResult;
    },
    hasImgUpload() {
      // 检查是否有需要上传的图片（base64格式的图片需要上传）
      return this.awardData.some((award) => {
        return award.prizeImg && award.prizeImg.indexOf('http') === -1 && award.prizeImg.indexOf('data:image') === 0;
      });
    },
    uploadImg() {
      return new Promise((resolve) => {
        if (this.hasImgUpload()) {
          // 这里简化处理，因为图片已经在选择时上传了
          // 实际项目中可能需要批量上传未上传的图片
          resolve();
        } else {
          resolve();
        }
      });
    },
    submitSetting() {
      if (!this.formValidate()) {
        return;
      }

      // 准备提交的数据
      const submitData = {
        gameTime: this.formData.gameTime,
        perPrice: this.formData.perPrice,
        prizeNum: this.awardData.length,
        awardData: this.awardData,
      };

      console.log('提交设置:', submitData);

      this.uploadImg().then(() => {
        return request.post('/qiYeNe/update', {
          splid: this.$store.state.liveId,
          pointJson: JSON.stringify(submitData),
        });
      }).then(() => {
        // console.log(res);
        this.$message.success('提交成功');
      }).catch(() => {
        // console.log(err);
        this.$message.error('提交失败');
      });
    },
    // 编辑奖项
    editAward(row, index) {
      this.currentEditIndex = index;
      this.editForm = {
        prizeName: row.prizeName,
        prizeImg: row.prizeImg,
      };
      this.editAwardDialog = true;
    },
    // 新增奖项
    addAward() {
      this.currentEditIndex = -1;
      this.editForm = {
        prizeName: '',
        prizeImg: '',
      };
      this.editAwardDialog = true;
    },
    // 保存奖项
    saveAward() {
      if (!this.editForm.prizeName) {
        this.$message.error('请填写奖品名称');
        return;
      }

      if (this.currentEditIndex === -1) {
        // 新增
        this.awardData.push({ ...this.editForm });
      } else {
        // 编辑
        this.$set(this.awardData, this.currentEditIndex, { ...this.editForm });
      }

      this.editAwardDialog = false;
      this.$message.success(this.currentEditIndex === -1 ? '新增成功' : '编辑成功');

      // 保存后自动提交到服务器
      this.autoSubmitAfterAwardChange();
    },
    // 取消编辑
    cancelEdit() {
      this.editAwardDialog = false;
      this.editForm = {
        prizeName: '',
        prizeImg: '',
      };
    },
    // 处理图片上传
    handleFile(e) {
      if (e.file.size > 21000000) {
        this.$message.error('上传图片不超过20M!');
        return;
      }
      if (!(e.file.type === 'image/jpeg' || e.file.type === 'image/png')) {
        this.$message.error('上传图片只能是jpg或png格式');
        return;
      }

      // 保存原始文件
      this.tempFile = e.file;

      const freader = new FileReader();
      freader.readAsDataURL(e.file); // 读取照片用于预览

      freader.onload = () => {
        this.editForm.prizeImg = freader.result;
        this.requestUploadFile();
      };
    },
    // 直接上传原始文件到服务器
    requestUploadFile() {
      // 直接使用原始文件，不进行Canvas处理
      const formData = new FormData();
      formData.append('file', this.tempFile);

      request
        .post('/beiJing/shangchuanTomcat', formData, { loading: 1 })
        .then((res) => {
          console.log('图片上传成功:', res);
          this.$message({
            message: '图片上传成功!',
            type: 'success',
          });
          this.editForm.prizeImg = res.data.filePath;
        })
        .catch((err) => {
          console.log(err);
          this.$message.error('图片上传失败!');
        });
    },
    // 奖项变更后自动提交
    autoSubmitAfterAwardChange() {
      // 准备提交的数据
      const submitData = {
        gameTime: this.formData.gameTime,
        perPrice: this.formData.perPrice,
        prizeNum: this.awardData.length,
        awardData: this.awardData,
      };

      console.log('奖项变更后自动提交:', submitData);

      this.uploadImg().then(() => {
        return request.post('/qiYeNe/update', {
          splid: this.$store.state.liveId,
          pointJson: JSON.stringify(submitData),
        });
      }).then((res) => {
        console.log('奖项变更提交成功:', res);
      }).catch((err) => {
        console.log('奖项变更提交失败:', err);
        this.$message.error('自动保存失败，请手动提交');
      });
    },
    // 获取表单数据
    getFormData() {
      getActivityMsg({
        id: this.$store.state.liveId,
      })
        .then((res) => {
          console.log(res);
          this.convertServerDataAndInitForm(res.data.pointJson);
        })
        .catch((err) => {
          console.log(err);
          // 如果接口调用失败，使用默认数据
          this.initDefaultData();
        });
    },
    // 解析服务器数据并初始化表单
    convertServerDataAndInitForm(jsonStr) {
      try {
        if (jsonStr && jsonStr.trim() !== '') {
          const tmpJsonObj = JSON.parse(jsonStr);
          this.formData.gameTime = tmpJsonObj.gameTime || 3;
          this.formData.perPrice = tmpJsonObj.perPrice || 18.8;
          this.formData.prizeNum = tmpJsonObj.prizeNum || 1;
          this.awardData = tmpJsonObj.awardData || [];
        } else {
          // 如果服务器返回空数据，使用默认数据
          this.initDefaultData();
        }
      } catch (error) {
        console.log(error);
        // 如果解析失败，使用默认数据
        this.initDefaultData();
      }
    },
    // 初始化默认数据
    initDefaultData() {
      this.formData.gameTime = 3;
      this.formData.perPrice = 18.8;
      this.awardData = [];
    },
    // 删除奖项
    deleteAward(index) {
      this.awardData.splice(index, 1);
      this.$message.success('删除成功');

      // 删除后自动提交到服务器
      this.autoSubmitAfterAwardChange();
    },
    // 删除确认对话框
    confirmDeleteAward(index) {
      // 检查是否只有一个奖项
      if (this.awardData.length <= 1) {
        this.$message.error('至少需要保留一个奖项');
        return;
      }

      this.$confirm('此操作将永久删除该奖项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.deleteAward(index);
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
  },
};
</script>

<style lang="less" scoped>
.settingForm {
  padding: 20px;
  .setting-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .setting-item-title {
      width: 120px;
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
    }
    .setting-item-content {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 10px;
      .el-input-number {
        width: 200px;
      }
    }
  }
  .submit-btn {
  }
}

// 奖项设置样式
.award-setting-section {
  margin-top: 30px;
  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
    margin-bottom: 20px;
    padding-left: 20px;
  }
  .award-table-container {
    .prize-img {
      display: flex;
      justify-content: center;
      align-items: center;
      .no-img-placeholder {
        width: 47px;
        height: 31px;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #c0c4cc;
        font-size: 16px;
      }
    }
    .add-award-btn {
      width: 96%;
      margin: 20px auto;
      height: 40px;
      border: 1px dashed #409eff;
      border-radius: 4px;
      text-align: center;
      line-height: 40px;
      cursor: pointer;
      color: #409eff;
      font-size: 14px;
      transition: all 0.3s;
      &:hover {
        border-color: #66b1ff;
        color: #66b1ff;
      }
    }
  }
}

// 弹窗样式
.dialog-title {
  .title-text {
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }
}

.edit-form {
  padding: 20px 0;
  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .form-label {
      width: 100px;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85);
    }
    .form-input {
      flex: 1;
      .el-input {
        width: 300px;
      }
      .image-upload {
        display: flex;
        align-items: center;
        gap: 15px;
        .image-preview {
          width: 80px;
          height: 50px;
          border: 1px dashed #d9d9d9;
          border-radius: 4px;
          display: flex;
          justify-content: center;
          align-items: center;
          overflow: hidden;
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          .no-image {
            color: #c0c4cc;
            font-size: 20px;
          }
        }
      }
    }
  }
}

.dialog-buttons {
  text-align: center;
  padding: 20px 0;
  .el-button {
    margin: 0 10px;
  }
}
</style>
